//请求函数
import { reqCartList ,reqUpdateCartChecked,reqDeleteCart} from "@/api";
import { getUserId } from "@/utils/USER_UUID";
//购物车小仓库地方
const state = {
      //存储用户临时身份【唯一、持久化】
      USER_ID:getUserId(),
      //用户购物车的数据
      shopList:[]
};
const mutations = {
    GETCARTLIST:(state,shopList)=>{
         state.shopList = shopList;
    }
}
const actions = {
    //getCartList类型的action-----获取购物车列表
    getCartList: async ({ commit, state, dispatch }) => {
        //获取到购物车的数据
        let result = await reqCartList();
        if(result.code==200){
            //提交mutation，存储用户购物车数据
            commit("GETCARTLIST",result.data);
        }
    },
    // updateChecked类型的action(修改某一商品的状态)
    updateChecked:async({ commit, state, dispatch },{skuId,isChecked})=>{
        let result =await reqUpdateCartChecked(skuId,isChecked);
        if(result.code==200) {
            return 'ok'
        }else {
            return Promise.reject();
        }
    },
    // 伤处某一商品
    deleteCart:async({ commit, state, dispatch},skuId)=>{
        let result = await reqDeleteCart(skuId);
        console.log(result);
        if(result.code==200) {
            return 'ok'
        }else {
            return Promise.reject();
        }
    },
    // 修改全部商品
    updateAllChecked:({commit,state,dispatch},isChecked)=>{
        let all=[];
        // 遍历购物车数组
        state.shopList[0].cartInfoList.forEach((item)=>{
            // 调用修改某一个商品action(N次:看数组元素个数)
            // 返回一个Promise,可能成功失败
            let promise=dispatch('updateChecked',{skuId:item.skuId,isChecked});
            all.push(promise);
            console.log(all);
        })
        return Promise.all(all);
    },
    // 删除选中的商品
    deleteCartByChecked:({ commit, state, dispatch})=>{
        let arr=[];
        // getters|state都可以获取到仓库数据
        state.shopList[0].cartInfoList.forEach(item=>{
            if(item.isChecked==1){
                let promise=dispatch("deleteCart",item.skuId);
                arr.push(promise);
            }
        })
        // 返回Promise
        return Promise.all(arr);
    }
};
const getters = {
      //简化购物车的数据
      shopCartList(state){
          return state.shopList[0]||{};
      }
};

//默认暴露:小仓库对外暴露的是对象,默认暴露
export default {
    state,
    mutations,
    actions,
    getters
}